﻿using System;
using System.Threading;
using System.Windows;
using Appology.SugarSync.IO;
using Microsoft.Phone.Controls;

namespace Appology.SugarSync.Explorer.Phone
{
    public partial class RenameFile : PhoneApplicationPage
    {
        public RenameFile()
        {
            InitializeComponent();
            DataContext = ApplicationState.Current.History.Pop();

            Loaded += RenameFile_Loaded;
        }

        void RenameFile_Loaded(object sender, RoutedEventArgs e)
        {
            FileName.Focus();

            if(FileName.Text.Contains("."))
            {
                var lastPeriod = FileName.Text.LastIndexOf(".");
                FileName.SelectionStart = 0;
                FileName.SelectionLength = lastPeriod;
            }
        }

        private async void Save_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(FileName.Text))
            {
                MessageBox.Show("File name is required.");
                return;
            }

            var fileInfo = (SugarSyncFileInfo) DataContext;

            //ApplicationState.Current.History.Push(fileInfo);

            await fileInfo.UpdateInfo(FileName.Text, fileInfo.ContentType);

            var timer = new Timer(o =>
            {
                Dispatcher.BeginInvoke(async () =>
                {
                    await fileInfo.RefreshAsync();
                    NavigationService.GoBack();
                });
            }, null, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(-1));
        }
    }
}